package com.yilin.tms.data.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yilin.commons.exception.BusinessException;
import com.yilin.commons.util.ArrayUtil;
import com.yilin.commons.util.CommonUtil;
import com.yilin.commons.util.DateTimeUtil;
import com.yilin.commons.util.JsonUtil;
import com.yilin.tms.core.application.PageData;
import com.yilin.tms.core.application.ReturnData;
import com.yilin.tms.core.application.ServiceUtil;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.commons.utils.QueryUtil;
import com.yilin.tms.core.entity.capital.TradeRecord;
import com.yilin.tms.core.entity.data.monitor.TmsDataSync;
import com.yilin.tms.core.entity.data.monitor.TmsRootData;
import com.yilin.tms.core.entity.data.monitor.wlhy.*;
import com.yilin.tms.core.entity.order.goods.GoodsOrderNoteDetail;
import com.yilin.tms.core.entity.order.payment.OrderSettlementCost;
import com.yilin.tms.core.entity.order.transit.TransitOrder;
import com.yilin.tms.core.entity.order.transit.TransitOrderNoteDetail;
import com.yilin.tms.core.entity.order.transit.TransitOrderVehicleRecord;
import com.yilin.tms.core.entity.system.param.TruckType;
import com.yilin.tms.core.entity.truck.TransportLicense;
import com.yilin.tms.core.entity.truck.TravelLicense;
import com.yilin.tms.core.entity.truck.TruckVehicle;
import com.yilin.tms.core.entity.user.OrganType;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.core.entity.user.auth.*;
import com.yilin.tms.core.entity.user.organize.Organize;
import com.yilin.tms.core.remote.*;
import com.yilin.tms.data.mapper.TmsDataSyncMapper;
import com.yilin.tms.data.mapper.TmsRootDataMapper;
import com.yilin.tms.data.service.ITmsDataService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/***
 * 省运管数据服务
 * */
@Service
public class TmsDataService extends ServiceImpl<TmsRootDataMapper, TmsRootData> implements ITmsDataService {

    @Resource
    private TmsRootDataMapper tmsRootDataMapper;
    @Resource
    private TmsDataSyncMapper tmsDataSyncMapper;

    @Resource
    private IGpsRemote gpsRemote;
    @Resource
    private IUserRemote userRemote;
    @Resource
    private IVehicleRemote vehicleRemote;
    @Resource
    private IOrderRemote orderRemote;
    @Resource
    private ICapitalRemote capitalRemote;

    /**
     * 查询区 分页查询
     * */
    @Override
    public PageData<TmsRootData> getTmsRootPage(TmsRootData tmsRootData, Integer page, Integer limit) {
        QueryWrapper<TmsRootData> queryWrapper = new QueryWrapper<>();
        QueryUtil.andQueryWrapper(queryWrapper, tmsRootData);
        return tmsRootDataMapper.selectPage(new PageData<>(page, limit),queryWrapper);
    }

    /**
     * 转移区 拷贝所有创建数据
     * */
    @Override
    public List<TmsRootData> copyTmsRootData(String platId) {
        //获取平台已转移数据记录，存在即已转移
        QueryWrapper<TmsDataSync> syncWrapper = new QueryWrapper<>();
        syncWrapper.eq("plat_id",platId);
        List<TmsDataSync> tmsDataSyncList = tmsDataSyncMapper.selectList(syncWrapper);
        List<String> dataIdList = ArrayUtil.fieldAdd(tmsDataSyncList, TmsDataSync::getTmsDataId);
        //-----------------------------------------------------------------------------------
        QueryWrapper<TmsRootData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", TmsRootData.Status.createSuccess.index);
        if (!dataIdList.isEmpty()) queryWrapper.notIn("id",dataIdList);//未转移
        queryWrapper.and(wrapper -> wrapper.isNull("plat_id").or().eq("plat_id",platId));
        return tmsRootDataMapper.selectList(queryWrapper);
    }

    /**
     * 同步区 同步指定数据状态
     * */
    @Override
    public void syncTmsRootData(String platId, String platName, List<String> ids, TmsDataSync.SyncStatus status) {
        List<TmsRootData> tmsRootDataList = tmsRootDataMapper.selectBatchIds(ids);
        tmsRootDataList.forEach(tmsRootData -> {
            QueryWrapper<TmsDataSync> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("plat_id",platId);
            queryWrapper.eq("tms_data_id",tmsRootData.getId());
            TmsDataSync tmsDataSync = tmsDataSyncMapper.selectOne(queryWrapper);
            if (tmsDataSync==null) tmsDataSync = new TmsDataSync();
            tmsDataSync.setDocumentName(tmsRootData.getDocumentName());
            tmsDataSync.setIdentification(tmsRootData.getIdentification());
            tmsDataSync.setTmsDataId(tmsRootData.getId());
            tmsDataSync.setPlatId(platId);
            tmsDataSync.setPlatName(platName);
            tmsDataSync.setStatus(status);
            if (tmsDataSync.getId() != null){
                tmsDataSyncMapper.updateById(tmsDataSync);
            } else {
                tmsDataSyncMapper.insert(tmsDataSync);
            }
        });
    }

    /**
     * 自动生成：车辆信息单
     */
    @Override
    public void autoSaveVehicleOrder() {
        //获取平台未生成或生产失败的数据
        ReturnData<List<TruckVehicle>> vehicleList = vehicleRemote.getErrorTmsVehicle();
        vehicleList.getData().forEach(this::saveTmsCL1001);
    }

    /**
     * 自动生成：驾驶员信息单
     */
    @Override
    public void autoSaveDriverOrder() {
        //获取平台未生成或生产失败的数据
        String safeKey = ServiceUtil.saveServiceSafeNotify("getErrorTmsAccount");
        ReturnData<List<Account>> truckUserList = userRemote.getErrorTmsAccount(safeKey);
        truckUserList.getData().forEach(this::saveTmsJSY1001);
    }

    /**
     * 自动生成：运单信息单
     */
    @Override
    public void autoSaveTransitOrder() {
        //获取平台未生成或生产失败的数据
        ReturnData<List<TransitOrder>> transitOrderList = orderRemote.getErrorTmsTransitOrder(null);
        transitOrderList.getData().forEach(this::saveTmsYD1001);
    }

    /**
     * 自动生成：挂车信息补传单
     */
    @Override
    public void autoSaveTransitTrailerOrder() {
        //获取平台未生成或生产失败的数据
        ReturnData<List<TransitOrder>> transitOrderList = orderRemote.getErrorTmsTransitOrder(TruckType.TowingType.trailer.index);
        transitOrderList.getData().forEach(this::saveTmsYDGC1001);
    }

    /**
     * 自动生成：资金流水单
     */
    @Override
    public void autoSaveCapitalFlowOrder() {
        //获取平台未生成或生产失败的数据
        ReturnData<List<TradeRecord>> tradeRecordList = capitalRemote.getErrorTmsTradeRecord();
        tradeRecordList.getData().forEach(this::saveTmsZJ1001);
    }


    //基础数据生成：车辆信息单
    @Override
    public void saveTmsCL1001(TruckVehicle truckVehicle) {
        TmsRootData tmsRootData = getTmsRootDataByIdentification(truckVehicle.getTrackNo());
        if (tmsRootData == null) tmsRootData = new TmsRootData();
        if (tmsRootData.getStatus() != null && tmsRootData.getStatus() != TmsRootData.Status.createFail) return;
        tmsRootData.setIdentification(truckVehicle.getTrackNo());//唯一标识
        tmsRootData.setDocumentName("车辆信息单");
        tmsRootData.setIpcType("WLHY_CL1001");
        tmsRootData.setAutoPostCount(0);
        try {
            TravelLicense travelLicense = ParamUtil.isSuccess(vehicleRemote.getTravelLicenseByVehicleId(truckVehicle.getId()));
            TransportLicense transportLicense = ParamUtil.isSuccess(vehicleRemote.getTransportLicenseByVehicleId(truckVehicle.getId()));
            if (travelLicense == null) throw new BusinessException("车辆行驶证未找到");
            TmsCL1001 tmsCL1001 = new TmsCL1001();
            tmsCL1001.setGrossMass(CommonUtil.formatDoubleTwo(travelLicense.getVehicleWeight()));
            tmsCL1001.setVehicleTonnage(CommonUtil.formatDoubleTwo(travelLicense.getLoadingWeight()));
            tmsCL1001.setIssueDate(DateTimeUtil.getDateTimeByStr(travelLicense.getIssueDate()));
            tmsCL1001.setIssuingOrganizations(travelLicense.getIssuingOrganizations());
            tmsCL1001.setOwner(travelLicense.getOwner());
            tmsCL1001.setRegisterDate(DateTimeUtil.getDateTimeByStr(travelLicense.getRegisterDate()));
            tmsCL1001.setUseCharacter(travelLicense.getUsageCharacteristics());
            tmsCL1001.setRemark("");
            if (truckVehicle.getVehicleWeight() > 4.5) {
                if (transportLicense == null) throw new BusinessException("车辆大于4.5吨，但是没有找到道路运输证");
                tmsCL1001.setRoadTransportCertificateNumber(transportLicense.getTransLicenseNo());
            } else {
//                String adCode = ParamUtil.isSuccess(gpsRemote.getAdCodeByAddress(truckVehicle.getPlatId(), travelLicense.getAddress()));
//                if (adCode == null || adCode.length() != 6) throw new BusinessException("保存车辆信息单时，从高德获得的地理编码区域码为空");
//                tmsCL1001.setRoadTransportCertificateNumber(String.format("%s000000", adCode));
            }
            tmsCL1001.setVehicleNumber(truckVehicle.getTrackNo());
            tmsCL1001.setVehicleType(truckVehicle.getTruckTypeCode());
            tmsCL1001.setVehiclePlateColorCode(truckVehicle.getCardPlateCode());
            tmsCL1001.setVehicleEnergyType(truckVehicle.getTruckEnergyTypeCode());
            tmsCL1001.setVin(travelLicense.getVehicleIdentifyCode());
            tmsRootData.setJsonContent(JsonUtil.objectToJson(tmsCL1001));
            tmsRootData.setStatus(TmsRootData.Status.createSuccess);
            tmsRootData.setReturnMsg("数据创建成功，等待提交");
        } catch (Exception e) {
            tmsRootData.setJsonContent(null);
            tmsRootData.setStatus(TmsRootData.Status.createFail);
            tmsRootData.setReturnMsg(String.format("数据创建失败，%s", e.getMessage()));
        } finally {
            saveOrUpdate(tmsRootData);
        }
    }

    // 基础数据生成：驾驶员信息单
    @Override
    public void saveTmsJSY1001(Account truckUser) {
        IdCard idcard = ParamUtil.isSuccess(userRemote.getIdCardByUserId(truckUser.getId()));
        TmsRootData tmsRootData = getTmsRootDataByIdentification(idcard.getIdCardNo());
        if (tmsRootData == null) tmsRootData = new TmsRootData();
        if (tmsRootData.getStatus() != null && tmsRootData.getStatus() != TmsRootData.Status.createFail) return;
        tmsRootData.setIdentification(idcard.getIdCardNo());//唯一标识
        tmsRootData.setDocumentName("驾驶员信息单");
        tmsRootData.setIpcType("WLHY_JSY1001");
        tmsRootData.setAutoPostCount(0);
        try {
            TmsJSY1001 tmsJSY1001 = new TmsJSY1001();
            DrivingLicense drivingLicense = ParamUtil.isSuccess(userRemote.getDrivingLicenseByUserId(truckUser.getId()));
            if (drivingLicense == null) throw new BusinessException("驾驶员驾驶证未找到！");
            QualificationCert qualificationCert = ParamUtil.isSuccess(userRemote.getQualificationCertByUserId(truckUser.getId()));
            tmsJSY1001.setVehicleClass(drivingLicense.getDrivingLicenseType());
            tmsJSY1001.setDrivingLicense(drivingLicense.getDrivingLicenseNo());
            tmsJSY1001.setDriverName(drivingLicense.getDrivingLicenseName());
            tmsJSY1001.setIssuingOrganizations(drivingLicense.getIssuingOrganizations());
            if (qualificationCert == null) {
                String idCardNoSix = StrUtil.sub(idcard.getIdCardNo(), 0, 6);
                tmsJSY1001.setQualificationCertificate(String.format("%s000000000000", idCardNoSix));
            } else {
                tmsJSY1001.setQualificationCertificate(qualificationCert.getOccupationalRequirementsNo());
            }
            tmsJSY1001.setRemark("");
            tmsJSY1001.setTelephone(truckUser.getPhone());
            tmsJSY1001.setValidPeriodFrom(DateTimeUtil.getDateTimeByShortStr(drivingLicense.getValidStartDate()));
            tmsJSY1001.setValidPeriodTo(DateTimeUtil.getDateTimeByShortStr(drivingLicense.getValidEndDate()));
            tmsRootData.setJsonContent(JsonUtil.objectToJson(tmsJSY1001));
            tmsRootData.setStatus(TmsRootData.Status.createSuccess);
            tmsRootData.setReturnMsg("数据创建成功，等待提交");
        } catch (Exception e) {
            tmsRootData.setJsonContent(null);
            tmsRootData.setStatus(TmsRootData.Status.createFail);
            tmsRootData.setReturnMsg(String.format("数据创建失败，%s", e.getMessage()));
        } finally {
            saveOrUpdate(tmsRootData);
        }
    }

    // 基础数据生成：保存运单信息单
    @Override
    public void saveTmsYD1001(TransitOrder transitOrder) {
        TmsRootData tmsRootData = getTmsRootDataByIdentification(transitOrder.getTransportNo());
        if (tmsRootData == null) tmsRootData = new TmsRootData();
        if (tmsRootData.getStatus() != null && tmsRootData.getStatus() != TmsRootData.Status.createFail) return;
//        tmsRootData.setIdentification(transitOrder.getTransportNo());//唯一标识
//        tmsRootData.setPlatId(transitOrder.getPlatId());
//        tmsRootData.setPlatName(transitOrder.getPlatName());
        tmsRootData.setDocumentName("电子运单");
        tmsRootData.setIpcType("WLHY_YD1001");
        tmsRootData.setAutoPostCount(0);
        try {
            TmsYD1001 tmsYD1001 = new TmsYD1001();
//            Organize wlhyPlat = ParamUtil.isSuccess(userRemote.getOrganizeById(transitOrder.getPlatId()));
//            if (wlhyPlat == null) throw new BusinessException("网络货运经营者（网货平台）未找到！");
            Organize shipperOrganize = ParamUtil.isSuccess(userRemote.getOrganizeById(transitOrder.getShipperOrganizeId()));
            if (shipperOrganize == null) throw new BusinessException("货主未找到！");
            Organize robOrganize = ParamUtil.isSuccess(userRemote.getOrganizeById(transitOrder.getRobOrganizeId()));
            if (robOrganize == null) throw new BusinessException("车主未找到！");
            TruckVehicle truckVehicle = ParamUtil.isSuccess(vehicleRemote.getVehicleById(transitOrder.getTransitTruckId()));
            if (truckVehicle == null) throw new BusinessException("车辆未找到！");
//            BusinessLicense businessLicense = ParamUtil.isSuccess(userRemote.getBusinessLicenseByOrganizeId(transitOrder.getPlatId()));
//            if (businessLicense == null) throw new BusinessException("网货平台营业执照未找到！");
//            TransBusinessLicense transBusinessLicense = ParamUtil.isSuccess(userRemote.getTransLicenseByOrganizeId(transitOrder.getPlatId()));
//            if (transBusinessLicense == null) throw new BusinessException("网货平台道路运输经营许可证未找到！");
            TmsYD1001.ActualCarrierInfo actualCarrierInfo = new TmsYD1001.ActualCarrierInfo();
            if (robOrganize.getOrganType() != OrganType.individual) {
                BusinessLicense license = ParamUtil.isSuccess(userRemote.getBusinessLicenseByOrganizeId(robOrganize.getId()));
                if (license == null) throw new BusinessException("承运企业营运执照未找到！");
                TransBusinessLicense transLicense = ParamUtil.isSuccess(userRemote.getTransLicenseByOrganizeId(robOrganize.getId()));
                if (transLicense == null) throw new BusinessException("承运企业道路运输经营许可证未找到！");
                actualCarrierInfo.setActualCarrierBusinessLicense(transLicense.getTransBusinessLicenseNo());
                actualCarrierInfo.setActualCarrierID(license.getBusinessNo());
                actualCarrierInfo.setActualCarrierName(license.getName());
            } else {
                IdCard idCard = ParamUtil.isSuccess(userRemote.getIdCardByUserId(robOrganize.getManagerUserId()));
                TravelLicense travelLicense = ParamUtil.isSuccess(vehicleRemote.getTravelLicenseByVehicleId(truckVehicle.getId()));
//                String adCode = ParamUtil.isSuccess(gpsRemote.getAdCodeByAddress(travelLicense.getPlatId(), travelLicense.getAddress()));
//                if (adCode == null || adCode.length() != 6) throw new BusinessException("保存运单信息单时，从高德获得的地理编码区域码为空");
//                actualCarrierInfo.setActualCarrierBusinessLicense(String.format("%s000000", adCode));
                actualCarrierInfo.setActualCarrierID(idCard.getIdCardNo());
                actualCarrierInfo.setActualCarrierName(idCard.getName());
            }
            tmsYD1001.setActualCarrierInfo(actualCarrierInfo);
            //收货人信息
            TmsYD1001.ConsigneeInfo consigneeInfo = new TmsYD1001.ConsigneeInfo();
            consigneeInfo.setConsignee(transitOrder.getPlanningConsigneeName());
            consigneeInfo.setConsigneeID(null);//收货人证件（不填）
            consigneeInfo.setCountrySubdivisionCode(transitOrder.getPlanningConsigneeAdCode());
            consigneeInfo.setGoodsReceiptPlace(transitOrder.getPlanningConsigneeAddress());
            tmsYD1001.setConsigneeInfo(consigneeInfo);
            tmsYD1001.setConsignmentDateTime(DateTimeUtil.getDateTimeByStr(transitOrder.getCreateTime()));
            //托运人信息
            TmsYD1001.ConsignorInfo consignorInfo = new TmsYD1001.ConsignorInfo();
            consignorInfo.setConsignor(transitOrder.getPlanningConsignorName());
            if (shipperOrganize.getOrganType() != OrganType.individual) {
                BusinessLicense license = ParamUtil.isSuccess(userRemote.getBusinessLicenseByOrganizeId(shipperOrganize.getId()));
                consignorInfo.setConsignorID(license.getBusinessNo());
            } else {
                IdCard idCard = ParamUtil.isSuccess(userRemote.getIdCardByUserId(shipperOrganize.getManagerUserId()));
                consignorInfo.setConsignorID(idCard.getIdCardNo());
            }
            consignorInfo.setCountrySubdivisionCode(transitOrder.getPlanningConsignorAdCode());
            consignorInfo.setPlaceOfLoading(transitOrder.getPlanningConsignorAddress());
            tmsYD1001.setConsignorInfo(consignorInfo);
            tmsYD1001.setDespatchActualDateTime(DateTimeUtil.getDateTimeByStr(transitOrder.getDeliverTime()));
            tmsYD1001.setGoodsReceiptDateTime(DateTimeUtil.getDateTimeByStr(transitOrder.getReceiptTime()));
            //保险信息
            TmsYD1001.InsuranceInformation insuranceInformation = new TmsYD1001.InsuranceInformation();
            insuranceInformation.setInsuranceCompanyCode("QITA");//保险公司代码 wlhy.mot.gov.cn
            insuranceInformation.setPolicyNumber("none");//保险单号
            tmsYD1001.setInsuranceInformation(insuranceInformation);
            tmsYD1001.setOriginalDocumentNumber(transitOrder.getGoodsOrderNo());
//            tmsYD1001.setPermitNumber(transBusinessLicense.getTransBusinessLicenseNo());
//            tmsYD1001.setRemark("");
//            tmsYD1001.setSendToProDateTime(DateTimeUtil.getDateTimeByStr(new Date()));
//            tmsYD1001.setSerialNumber("0000");
//            tmsYD1001.setShippingNoteNumber(transitOrder.getTransportNo());
//            tmsYD1001.setTotalMonetaryAmount(CommonUtil.formatDoubleThree(transitOrder.getShipperActualPayCost()));
//            tmsYD1001.setTransportTypeCode("1");//公路运输
//            tmsYD1001.setBusinessTypeCode(transitOrder.getTransportTypeCode());
//            tmsYD1001.setCarrier(wlhyPlat.getOrganizeName());
//            tmsYD1001.setUnifiedSocialCreditIdentifier(businessLicense.getBusinessNo());//统一社会信用代码
            tmsYD1001.setVehicleAmount("1");
            //车辆信息
            List<TmsYD1001.VehicleInfo> vehicleInfoList = new ArrayList<>();
            List<TransitOrderVehicleRecord> vehicleRecordList = ParamUtil.isSuccess(orderRemote.getTransitVehicleRecordList(transitOrder.getId()));
            for (TransitOrderVehicleRecord record : vehicleRecordList) {
                TmsYD1001.VehicleInfo vehicleInfo = new TmsYD1001.VehicleInfo();
                TruckVehicle truck = ParamUtil.isSuccess(vehicleRemote.getVehicleById(record.getTransitTruckId()));
                vehicleInfo.setDespatchActualDateTime(DateTimeUtil.getDateTimeByStr(record.getSplitStartTime()));
                vehicleInfo.setGoodsReceiptDateTime(DateTimeUtil.getDateTimeByStr(record.getSplitEndTime()));
                vehicleInfo.setGoodsReceiptPlace(record.getSplitConsigneeAddress());
                vehicleInfo.setReceiptCountrySubdivisionCode(record.getSplitConsigneeAdCode());
                vehicleInfo.setPlaceOfLoading(record.getSplitConsignorAddress());
                vehicleInfo.setLoadingCountrySubdivisionCode(record.getSplitConsignorAdCode());
                vehicleInfo.setVehicleNumber(truck.getTrackNo());
                vehicleInfo.setVehiclePlateColorCode(truck.getCardPlateCode());
                //挂车信息：非补传
                if (record.getTransitTrailerId() != null) {
                    TruckVehicle trailer = ParamUtil.isSuccess(vehicleRemote.getVehicleById(record.getTransitTrailerId()));
                    vehicleInfo.setTrailerVehiclePlateNumber(trailer.getTrackNo());
                    vehicleInfo.setTrailerVehiclePlateColorCode(trailer.getCardPlateCode());
                }
                //驾驶员信息
                List<TmsYD1001.VehicleInfo.DriverInfo> driverList = new ArrayList<>();
                TmsYD1001.VehicleInfo.DriverInfo driverInfo = new TmsYD1001.VehicleInfo.DriverInfo();
                DrivingLicense drivingLicense = ParamUtil.isSuccess(userRemote.getDrivingLicenseByUserId(record.getTransitTruckUserId()));
                driverInfo.setDriverName(drivingLicense.getDrivingLicenseName());
                driverInfo.setDrivingLicense(drivingLicense.getDrivingLicenseNo());
                driverList.add(driverInfo);
                vehicleInfo.setDriver(driverList);
                //货物信息
                List<TmsYD1001.VehicleInfo.GoodsInfo> goodsInfoList = new ArrayList<>();
                List<TransitOrderNoteDetail> detailList = ParamUtil.isSuccess(orderRemote.getAllTransitDetailList(transitOrder.getId()));
                for (TransitOrderNoteDetail transitOrderNoteDetail : detailList) {
                    GoodsOrderNoteDetail goodsOrderNoteDetail = transitOrderNoteDetail.getGoodsOrderNoteDetail();
                    TmsYD1001.VehicleInfo.GoodsInfo goodsInfo = new TmsYD1001.VehicleInfo.GoodsInfo();
                    goodsInfo.setCargoTypeClassificationCode(goodsOrderNoteDetail.getGoodsTypeCode());
                    goodsInfo.setDescriptionOfGoods(goodsOrderNoteDetail.getGoodsName());
                    // 根据运输比 计算司机重量估值
                    double rate = transitOrderNoteDetail.getAssignMeasure() / goodsOrderNoteDetail.getGoodsMeasure();
                    goodsInfo.setGoodsItemGrossWeight(CommonUtil.formatDoubleThree(goodsOrderNoteDetail.getGrossWeight() * rate));
                    goodsInfo.setCube("1.0000");//（选）
                    goodsInfo.setTotalNumberOfPackages("1");//（选）
                    goodsInfoList.add(goodsInfo);
                }
                vehicleInfo.setGoodsInfo(goodsInfoList);
                vehicleInfoList.add(vehicleInfo);
            }
            tmsYD1001.setVehicleInfo(vehicleInfoList);
            tmsRootData.setJsonContent(JsonUtil.objectToJson(tmsYD1001));
            tmsRootData.setStatus(TmsRootData.Status.createSuccess);
            tmsRootData.setReturnMsg("数据创建成功，等待提交");

        } catch (Exception e) {
            tmsRootData.setJsonContent(null);
            tmsRootData.setStatus(TmsRootData.Status.createFail);
            tmsRootData.setReturnMsg(String.format("数据创建失败，%s", e.getMessage()));
        } finally {
            saveOrUpdate(tmsRootData);
        }
    }

    // 基础数据生成：挂车信息补传单
    @Override
    public void saveTmsYDGC1001(TransitOrder transitOrder) {
        if (transitOrder.getTransitTrailerId() == null) return;
        TruckVehicle trailer = ParamUtil.isSuccess(vehicleRemote.getVehicleById(transitOrder.getTransitTrailerId()));
        TmsRootData tmsRootData = getTmsRootDataByIdentification(transitOrder.getTransportNo() + trailer.getTrackNo());
        if (tmsRootData == null) tmsRootData = new TmsRootData();
        if (tmsRootData.getStatus() != null && tmsRootData.getStatus() != TmsRootData.Status.createFail) return;
        tmsRootData.setIdentification(transitOrder.getTransportNo() + trailer.getTrackNo());//唯一标识 挂车车牌号+运单号
//        tmsRootData.setPlatId(transitOrder.getPlatId());
//        tmsRootData.setPlatName(transitOrder.getPlatName());
        tmsRootData.setDocumentName("挂车信息补全单");
        tmsRootData.setIpcType("WLHY_YDGC1001");
        tmsRootData.setAutoPostCount(0);
        try {
            TmsYDGC1001 tmsYDGC1001 = new TmsYDGC1001();
            tmsYDGC1001.setTrailerVehiclePlateNumber(trailer.getTrackNo());
            tmsYDGC1001.setTrailerVehiclePlateColorCode(trailer.getCardPlateCode());
            List<TmsYDGC1001.ShippingNoteNumber> shippingNoteNumbers = new ArrayList<>();
            TmsYDGC1001.ShippingNoteNumber shippingNoteNumber = new TmsYDGC1001.ShippingNoteNumber();
            shippingNoteNumber.setSerialNumber("0000");
            shippingNoteNumber.setShippingNoteNumber(transitOrder.getTransportNo());
            shippingNoteNumbers.add(shippingNoteNumber);
            tmsYDGC1001.setShippingNoteNumbers(shippingNoteNumbers);
            tmsRootData.setJsonContent(JsonUtil.objectToJson(tmsYDGC1001));
            tmsRootData.setStatus(TmsRootData.Status.createSuccess);
            tmsRootData.setReturnMsg("数据创建成功，等待提交");
        } catch (Exception e) {
            tmsRootData.setJsonContent(null);
            tmsRootData.setStatus(TmsRootData.Status.createFail);
            tmsRootData.setReturnMsg(String.format("数据创建失败，%s", e.getMessage()));
        } finally {
            saveOrUpdate(tmsRootData);
        }
    }

    // 基础数据生成：资金流水单
    @Override
    public void saveTmsZJ1001(TradeRecord tradeRecord) {
        TmsRootData tmsRootData = getTmsRootDataByIdentification(tradeRecord.getTradeNo());
        if (tmsRootData == null) tmsRootData = new TmsRootData();
        if (tmsRootData.getStatus() != null && tmsRootData.getStatus() != TmsRootData.Status.createFail) return;
        tmsRootData.setIdentification(tradeRecord.getTradeNo());//唯一标识 流水单号
//        tmsRootData.setPlatId(tradeRecord.getPlatId());
//        tmsRootData.setPlatName(tradeRecord.getPlatName());
        tmsRootData.setDocumentName("资金流水单");
        tmsRootData.setIpcType("WLHY_ZJ1001");
        tmsRootData.setAutoPostCount(0);
        try {
            TmsZJ1001 tmsZJ1001 = new TmsZJ1001();
//            List<Map<String, Object>> paymentMapList = JsonUtil.jsonToObject(tradeRecord.getOrderPaymentIds(), new TypeToken<List<Map<String, Object>>>() {});
//            List<String> paymentNoList = ArrayUtil.fieldAdd(paymentMapList, map -> (String) map.get("transportNo"));
            List<OrderSettlementCost> paymentList = ParamUtil.isSuccess(orderRemote.getOrderSettlementListByIds(tradeRecord.getOrderPaymentIds()));
            if (paymentList == null || paymentList.size() == 0) throw new BusinessException("预付单列表为空");
            TransitOrder first = ParamUtil.isSuccess(orderRemote.getTransitOrderById(ArrayUtil.first(paymentList).getTransitOrderId()));
            Organize robOrganize = ParamUtil.isSuccess(userRemote.getOrganizeById(first.getRobOrganizeId()));
            TruckVehicle truckVehicle = ParamUtil.isSuccess(vehicleRemote.getVehicleById(first.getTransitTruckId()));
            tmsZJ1001.setDocumentNumber(tradeRecord.getTradeNo());
            if (robOrganize.getOrganType() != OrganType.individual) {
                BusinessLicense license = ParamUtil.isSuccess(userRemote.getBusinessLicenseByOrganizeId(robOrganize.getId()));
                tmsZJ1001.setActualCarrierID(license.getBusinessNo());
                tmsZJ1001.setCarrier(license.getName());
            } else {
                IdCard idCard = ParamUtil.isSuccess(userRemote.getIdCardByUserId(robOrganize.getManagerUserId()));
                tmsZJ1001.setActualCarrierID(idCard.getIdCardNo());
                tmsZJ1001.setCarrier(idCard.getName());
            }
            tmsZJ1001.setSendToProDateTime(DateTimeUtil.getDateTimeByStr(new Date()));
            tmsZJ1001.setVehicleNumber(truckVehicle.getTrackNo());
            tmsZJ1001.setVehiclePlateColorCode(truckVehicle.getCardPlateCode());
            //财务列表
            List<TmsZJ1001.Financial> financialList = new ArrayList<>();
            TmsZJ1001.Financial financial = new TmsZJ1001.Financial();
            financial.setBankCode("ONEBANK");
            financial.setDateTime(DateTimeUtil.getDateTimeByStr(tradeRecord.getFinishTime()));
            financial.setMonetaryAmount(CommonUtil.formatDoubleThree(tradeRecord.getMoney()));
            financial.setPaymentMeansCode("32");//付款方式代码 32 -- 银行
            financial.setReceiptAccount(tradeRecord.getIncomeCapitalAccount());
            financial.setRecipient(tradeRecord.getIncomeOrganizeName());
            financial.setSequenceCode(tradeRecord.getBankFlowNo());
            financialList.add(financial);
            tmsZJ1001.setFinanciallist(financialList);
            //运单列表
            List<TmsZJ1001.ShippingNote> shippingNoteList = new ArrayList<>();
            for (OrderSettlementCost orderSettlementCost : paymentList) {
                TmsZJ1001.ShippingNote shippingNote = new TmsZJ1001.ShippingNote();
                shippingNote.setShippingNoteNumber(orderSettlementCost.getTransportNo());
                shippingNote.setSerialNumber("0000");
                //总金额：包括油卡、过路费等 就是货主付的运费
                shippingNote.setTotalMonetaryAmount(CommonUtil.formatDoubleThree(orderSettlementCost.getActualTransportCost()));
                shippingNoteList.add(shippingNote);
            }
            tmsZJ1001.setShippingNoteList(shippingNoteList);
            tmsRootData.setJsonContent(JsonUtil.objectToJson(tmsZJ1001));
            tmsRootData.setStatus(TmsRootData.Status.createSuccess);
            tmsRootData.setReturnMsg("数据创建成功，等待提交");
        } catch (Exception e) {
            tmsRootData.setJsonContent(null);
            tmsRootData.setStatus(TmsRootData.Status.createFail);
            tmsRootData.setReturnMsg(String.format("数据创建失败，%s", e.getMessage()));
        } finally {
            saveOrUpdate(tmsRootData);
        }
    }

    // 根据数据标识货物数据
    private TmsRootData getTmsRootDataByIdentification(String identification) {
        QueryWrapper<TmsRootData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("identification", identification);
        return tmsRootDataMapper.selectOne(queryWrapper);
    }
}

